﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.Log;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using static System.Net.Mime.MediaTypeNames;

namespace RCE.K3.YGJD.Service.PlugIn.BD
{

    [HotUpdate]
    [Description("物料审核 采购价格更新到采购价目表")]
    public class MaterialAudit : AbstractOperationServicePlugIn
    {

        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            foreach (var item in e.DataEntitys)
            {
                var logs = new List<LogObject>();
                try
                {
                    int materialId = Convert.ToInt32(item["Id"]);
                    DynamicObjectCollection MaterialPurchase = item["MaterialPurchase"] as DynamicObjectCollection;

                    int unitId = 0;
                    if (MaterialPurchase != null)
                    {
                        unitId = Convert.ToInt32(MaterialPurchase[0]["PurchasePriceUnitId_Id"]);
                    }
                    int materialType = 0;

                    DynamicObjectCollection MaterialBase = item["MaterialBase"] as DynamicObjectCollection;

                    decimal taxRate = 0;
                    if (MaterialBase != null)
                    {
                        materialType = Convert.ToInt32(MaterialBase[0]["CategoryID_Id"]);
                    }

                    List<List<string>> lists = getFieldKey();

                    foreach (var list in lists)
                    {
                        //采购未税价目表
                        int priceListId = Convert.ToInt32(item[list[1] + "_Id"]);
                        decimal taxPrice = Convert.ToDecimal(item[list[0]]);
                        var DObjTaxRateObj = item[list[2]] as DynamicObject;
                        if (DObjTaxRateObj != null)
                        {
                            taxRate = Convert.ToDecimal(DObjTaxRateObj["TaxRate"]);
                        }
                        if (priceListId > 0 && taxPrice > 0)
                        {
                            insertUpUpdate(priceListId, materialId, unitId, materialType, taxPrice, taxRate);
                        }
                    }
                }
                catch (Exception ex)
                {

                    LogObject logFail = new LogObject();
                    logFail.pkValue = "0";
                    logFail.Description = "出错原因：" + ex.Message;
                    logFail.OperateName = "物料添加价目表出错";
                    logFail.ObjectTypeId = "BD_MATERIAL";
                    logFail.SubSystemId = "BD";
                    logFail.Environment = OperatingEnvironment.BizOperate;
                    logs.Add(logFail);
                }
                if (logs.Count > 0)
                    LogServiceHelper.BatchWriteLog(this.Context, logs);
            }
        }

        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);

            e.FieldKeys.Add("FPurchasePriceUnitId");
            e.FieldKeys.Add("FTaxRateId");
            e.FieldKeys.Add("FCategoryID");
            e.FieldKeys.Add("FUseOrgId");
            e.FieldKeys.Add("F_UIXC_Decimal");
            e.FieldKeys.Add("F_UIXC_Decimal1");
            e.FieldKeys.Add("F_UIXC_Decimal2");
            e.FieldKeys.Add("F_UIXC_Decimal3");
            e.FieldKeys.Add("F_UIXC_Base1");
            e.FieldKeys.Add("F_UIXC_Base11");
            e.FieldKeys.Add("F_UIXC_Base12");
            e.FieldKeys.Add("F_UIXC_Base13");
            e.FieldKeys.Add("F_UIXC_Base2");
            e.FieldKeys.Add("F_UIXC_Base21");
            e.FieldKeys.Add("F_UIXC_Base22");
            e.FieldKeys.Add("F_UIXC_Base211");
        }

        public List<List<string>> getFieldKey()
        {
            List<List<string>> strings = new List<List<string>>
            {
                new List<string>() { "F_UIXC_Decimal", "F_UIXC_Base1", "F_UIXC_Base2" },
                new List<string>() { "F_UIXC_Decimal1", "F_UIXC_Base11", "F_UIXC_Base21" },
                new List<string>() { "F_UIXC_Decimal2", "F_UIXC_Base12", "F_UIXC_Base22" },
                new List<string>() { "F_UIXC_Decimal3", "F_UIXC_Base13", "F_UIXC_Base211" }
            };
            return strings;
        }

        private void insertUpUpdate(int priceListId, int materialId, int unitId, int materialType, decimal taxPrice, decimal taxRate)
        {
            int FEntryId = isExistsItem(priceListId, materialId);
            if (FEntryId > 0)
            {
                // updatePriceListEntry(FEntryId, taxPrice, taxRate);
            }
            else
            {
                inserPriceListEntry(priceListId, materialId, unitId, materialType, taxPrice, taxRate);
            }
        }

        private int isExistsItem(int priceListId, int materialId)
        {
            string sql = $"SELECT FENTRYID FROM T_PUR_PRICELISTENTRY WHERE FID = {priceListId} AND FMATERIALID = {materialId}";
            var dt = DBUtils.ExecuteDynamicObject(this.Context, sql);
            if (dt.Count > 0)
            {
                return Convert.ToInt32(dt[0]["FENTRYID"]);
            }
            return 0;
        }

        private int inserPriceListEntry(int priceListId, int materialId, int unitId, int materialType, decimal taxPrice, decimal taxRate)
        {
            decimal price = taxPrice / (1 + taxRate / 100);
            string sql = $@"/*dialect*/
declare @fid int = {priceListId}
declare @MaterialId int ={materialId}
declare @UnitId int = {unitId}
declare @MaterialType int = {materialType} 
declare @taxPrice decimal(18,6) = {taxPrice}
declare @taxRate decimal(18,6) = {taxRate}
declare @Price decimal(18,6) = {price}
declare @ENTRYID int
declare @fseq int = 0
insert into Z_PUR_PriceListEntry(Column1) values('1')
select @ENTRYID = @@IDENTITY
delete from Z_PUR_PriceListEntry
print @ENTRYID
select @fseq = max(fseq) + 1 from T_PUR_PRICELISTENTRY where fid = @fid
insert into t_PUR_PriceListEntry(FENTRYID,FID,FSEQ,FMATERIALID,FUNITID,FMATERIALTYPEID,
FPRICE,FUPPRICE,FDOWNPRICE,FEFFECTIVEDATE,FEXPIRYDATE,
FDISABLESTATUS,FPATIDENTITY,FTAXPRICE,FTAXRATE,FMMASTERID,FROWAUDITSTATUS,FDEFBASEDATAO,FPriceCoefficient)
select @ENTRYID,@fid,@fseq,@MaterialId,@UnitId,@MaterialType,
@Price,@taxPrice,@taxPrice,'2000-01-01','2099-01-01',
'B',LOWER( REPLACE( NEWID(),'-','')),@taxPrice,@taxRate,@MaterialId,'A','0',1
";
            return DBUtils.Execute(this.Context, sql);
        }

        private int updatePriceListEntry(int entryid, decimal taxPrice, decimal taxRate)
        {
            decimal price = taxPrice / (1 + taxRate / 100);
            string sql = $"/*dialect*/UPDATE T_PUR_PRICELISTENTRY SET FPRICE = {price}, FTAXPRICE = {taxPrice},FUPPRICE = {taxPrice},FDOWNPRICE = {taxPrice},FTAXRATE = {taxRate} WHERE FENTRYID = {entryid}";
            return DBUtils.Execute(this.Context, sql);
        }
    }
}
